<template>
  <div class="container">
    <!-- 创建商品按钮 -->
    <el-button type="primary" @click="popup = true;" class="button-create">新建商品</el-button>

    <!-- 退出按钮 -->
    <el-button type="danger" @click="logout" class="button-logout">退出</el-button>

    <!-- 商品信息列表 -->
    <el-table :data="renderList" class="custom-table" :default-sort="{ prop: 'date', order: 'descending' }">
      <el-table-column prop="traceNumber" label="溯源码">
        <template slot-scope="scope">
          <!-- 鼠标点击商品细节弹窗信息 -->
          <el-popover trigger="click" placement="top" @show="handlePopover(scope.row)" :width="700">
            <GoodDetail :good="popoverData" :block_pro="block_pro" :user="user"/>
            <div slot="reference">
              <span class="trace-number">{{ scope.row.traceNumber }}</span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名称">
      </el-table-column>
      <el-table-column prop="traceName" label="生产商">
      </el-table-column>
      <el-table-column prop="location" label="地址">
      </el-table-column>
      <el-table-column prop="date" label="生产时间" sortable>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination class="custom-pagination" background :hide-on-single-page="false"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currPage"
                   :page-sizes="[10, 20, 50]" :page-size.sync="pageSize" layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>
    <!-- 创建商品子组件 -->
    <createGoods :dialogFormVisible="popup" @popup="handlePopup" @confirmPopup="formSubmit" />
  </div>
</template>

<script>
import axios from 'axios';
import createGoods from '../components/createGoods.vue';
import GoodDetail from "../components/GoodDetail.vue";
export default {
  name: "Producer",
  data() {
    return {
      popup: false, // 创建商品弹窗
      goodsList: [], // 商品信息
      currPage: 1, // 当前页
      pageSize: 10, // 每页显示数据
      popoverData: {}, // 弹窗商品信息数据
      block_pro: {},   // 区块链信息
      total: 0, // 总数据
      user: 0
    }
  },
  components: {
    GoodDetail,
    createGoods
  },
  computed: {
    renderList() {
      return this.goodsList.slice((this.currPage - 1) * this.pageSize, this.currPage * this.pageSize)
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    logout() {
      this.$router.push({ name: 'loginview' });
      this.$emit('logout', '')
    },
    getData() {
      axios.get('/producing')
          .then(ret => {
            this.goodsList = ret.data
                .map(item => ({
                  ...item,
                  date: this.$dateTime(item.timestamp),
                  traceNumber: item.traceNumber,
                  traceName: item.from,
                  goodsName: item.name,
                  quality: item.quality,
                  location: item.location,
                }))
                .reverse();
            this.total = this.goodsList.length;
          })
          .catch(err => {
            console.log(err)
          })
    },
    handlePopup(val) {
      this.popup = val;
    },
    async handlePopover(data) {
      axios.get(`/trace?traceNumber=${data.traceNumber}`)
          .then(ret => {
            this.popoverData = ret.data[0] || []
          })

      axios.post('/getBlockInfo', {
        type: "producer",
        traceNumber: data.traceNumber
      }).then(ret => {
        this.popoverData = ret.data[0] || []
        this.block_pro = ret.data.blockInfo;
      })
    },
    formSubmit(val) {
      axios.post('/produce', {
        ...val,
        quality: parseInt(val.quality),
        producerAddress: localStorage.getItem('account')
      }).then(ret => {
        if (ret.data.ret !== 1) {
          if (ret.data.ret === 0 && ret.data.msg === 'traceNumber already exist') {
            this.$message({
              message: '该溯源码已存在，请重新创建',
              type: 'error',
              center: true
            });
          } else {
            this.$message({
              message: '提交失败',
              type: 'error',
              center: true
            });
          }
          return
        }
        this.$blockInfo.setBlockInfo("Pro" + val.traceNumber, ret.data.data);
        this.$message({
          message: '提交成功',
          type: 'success',
          center: true
        });
        this.getData();
      }).catch(err => {
        console.log(err)
      })
      this.popup = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currPage = val;
    },
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  margin: 20px auto;
  max-width: 1200px;
}

.button-create {
  margin-bottom: 20px;
  background-color: #1E90FF;
  border-color: #1E90FF;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.button-create:hover {
  background-color: #1C86EE;
  border-color: #1C86EE;
}

.button-logout {
  float: right;
  margin-right: 20px;
  background-color: #FF6347;
  border: none;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.button-logout:hover {
  background-color: #EE5C42;
}

.custom-table {
  border: none;
  border-radius: 10px;
  overflow: hidden;
  background-color: #fdfdfd;
}

.custom-table .el-table__header-wrapper {
  background-color: #f0f0f0;
}

.custom-table .el-table__body {
  background-color: #ffffff;
}

.trace-number {
  color: #1E90FF;
  cursor: pointer;
}

.trace-number:hover {
  text-decoration: underline;
}

.custom-pagination {
  text-align: center;
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.el-table th {
  background-color: #fafafa;
  color: #333;
  font-weight: bold;
}

.el-table td {
  padding: 12px 10px;
  font-size: 14px;
}

</style>
